import { onReachBottom } from '@dcloudio/uni-app'
import { merge, get } from 'lodash-es'
import { Ref, ref } from 'vue'
import useRequest, { type IUseRequestOptions } from './useRequest'
import { isEmpty } from '@/utils/format'

export interface RequestMoreOptions extends IUseRequestOptions {
  listKey?: string
  totalKey?: string
}

function getDefaultOptions(): RequestMoreOptions {
  return {
    listKey: 'lists',
    totalKey: 'count',
    immediate: true,
    method: 'get',
    config: {
      params: {
        page: 1,
        limit: 20,
      },
    },
  }
}

export default function <T, P = unknown>(
  api: string | ApiPromise<P, ListResource<T>>,
  options?: RequestMoreOptions,
) {
  const requestOptions = merge(getDefaultOptions(), options || {})
  const { run, data: response, loading } = useRequest<ListResource<T>, P>(api, requestOptions)
  const list = ref<T[]>([])

  const hasMore = computed(() => {
    if (!list.value.length) return false
    return get(response.value.data, requestOptions.totalKey, 0) > list.value.length
  })

  async function refresh<Params>(params?: Params) {
    list.value = []
    requestOptions.config.params.page = 1
    await run(params)
  }

  watch(
    () => response.value,
    () => {
      const data = get(response.value.data, requestOptions.listKey, [])
      if (data.length) {
        list.value = [...list.value, ...data]
      }
    },
  )

  onReachBottom(() => {
    // console.log('滚到底部了', list.value.length)
    if (hasMore.value) {
      requestOptions.config.params.page += 1
      run()
    }
  })

  return { loading, list, run, refresh }
}
